package com.youlu.campus.admin.config;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.common.exception.ApiErrorCode;
import com.youlu.campus.common.base.RestResultBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.CharEncoding;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class RefererInterceptor extends HandlerInterceptorAdapter {
    /**
     * 白名单
     */
    @Value("#{'${auth.refererDomain:}'.empty ? null : '${auth.refererDomain:}'.split(',')}")
    private String[] refererDomain;
//    private String[] refererDomain={"campus-admin-test.youlu.com","campus-admin-api-test.youlu.com"};
    /**
     * 是否开启referer校验
     */
    private Boolean check = true;


    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
//        if (!check) {
//            return true;
//        }
//        String referer = req.getHeader("referer");
//        log.info(":>>> referer:{}", referer);
//        if (Objects.isNull(referer) || StringUtils.isBlank(referer)) {
//            referer = "admin-api.gqgood.com";
//        }
//        String host = req.getServerName();
//        log.info(":>>> referer:{},Host:{}", referer, host);
//        // 验证非get请求
//        if (!"GET".equals(req.getMethod())) {
//            if (referer == null) {
//                // 状态置为404
//                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
//                log.error(":>>> referer:空  ");
//                return false;
//            }
//            java.net.URL url = null;
//            try {
//                url = new java.net.URL(referer);
//                log.info(":>>> url:{}", url);
//            } catch (MalformedURLException e) {
//                // URL解析异常，也置为404
//                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
//                return false;
//            }
//            // 首先判断请求域名和referer域名是否相同
//            log.info(":.>> 请求域名:{},referer域名:{}", host, url.getHost());
//            if (!host.equals(url.getHost())) {
//                log.info(":>>> 不相等,判断白名单:{}", JSON.toJSONString(refererDomain));
//                // 如果不等，判断是否在白名单中
//                if (refererDomain != null) {
//                    for (String s : refererDomain) {
//                        if (s.equals(url.getHost())) {
//                            log.info(":.>> referer域名 验证OK");
//                            return true;
//                        }
//                    }
//                }
//                log.info(":.>> referer域名 验证NO");
//                outJson(resp, AuthErrorCode.INVALID_REQUEST);
//
//            }
//        }
        log.info(":.>> referer域名 验证OK");
        return true;
    }

    public void outJson(ServletResponse response, ApiErrorCode errorCode) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding(CharEncoding.UTF_8);//设置编码
            response.setContentType("application/json; charset=utf-8");//设置返回类型
            out = response.getWriter();
            out.println(JSON.toJSONString(RestResultBuilder.builder().errorCode(errorCode).build()));//输出
        } catch (Exception e) {
            log.error("json out error:{}", e.getMessage());
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }
}
